{% extends "mdm/basemdm.html" %}

{% block title %} {{ titulo }} {% endblock %}

{% block contenido %}
     <div id="contenido">
          <div id="izq">
               <div id="promociones">
                    {% for promo in promos  %}
                        <div  id="divpromo_{{ promo.id }}">
                              <h3 id="promo{{ promo.id }}"><a href="#">{{ promo.titulo }}</a></h3>
                         </div>
                    {% endfor %}
               </div>
          </div>
          <div id="der" class="sombra ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
               <h4>Texto</h4>
               <textarea id="texto" name="texto"></textarea>
               <div class="demo ui-widget ui-helper-clearfix">
                    <div id="fotoscon" class="ui-widget-content ui-state-default">
                         <h4 class="ui-widget-header"><span>Fotos de contenido<button id="newfp" href="#" rel="FP">A&ntilde;adir foto</button></span></h4>
                         <ul id="FPul" class="gallery ui-helper-reset ui-helper-clearfix"></ul>
                    </div>
               </div>
               <button id="guardar1">Guardar</button>
          </div>                    
     </div>
     <div id="up_div">
          <div class="upload_div ui-dialog ui-widget ui-widget-content ui-corner-all" title="A&ntilde;adir fotos">
               <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span class="ui-dialog-title" id="ui-dialog-title-1">Añadir fotos</span></div>
               <div class="c">
                    <div id="upload_btn"></div>
                    <div id="divStatus">0 archivos subidos</div>
                    <div id="fsUploadProgress" class="fieldset flash"></div>
               </div>
               <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                    <div class="ui-dialog-buttonset"><button id="cerrarFrm" href="#">Cerrar</button></div>
               </div>
          </div>
     </div>

{% endblock  %}

{% block script %}
     <script>
     var actual = ''
     var tabactual = 0
     var fotosya = false
     var promoya = false
     var dirty = false
     var stop = false
     var swfu
     
     var params = {'{{session_cookie_name}}': '{{session_key}}', '{{ csrf_token_name }}': '{{ csrf_token }}'}
     $(
          function() {

               $( "#promociones h3" ).click(
                    function( event ) {
                          var adelante = true
                         if (dirty) adelante = confirm('Hay cambios sin guardar. ¿Continuar?')
                         if (adelante) {
                              params['promo_id'] = $(this).attr('id').replace('promo', '')
                                   cargaPromo($(this).attr('id'))
                         }
                    }
               )

               $( "#promociones" ).accordion(
                    {
                         header: '> div > h3',
                         icons: { 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-circle-triangle-e' }
                    }
               )
               
               $('#guardar1').button().click(
                    function(event, ui) { 
                         guardar()
                         event.stopImmediatePropagation()
                         event.preventDefault()
                    }
               )
               
               $('input').change(
                    function(event, ui){
                         hayCambios()
                    }
               )
               
               tinyMCE.init(
                    {
                    mode : 'exact',
                    elements : 'texto',
                    theme : 'advanced',
                    plugins: 'fullscreen',
                    theme_advanced_buttons1 : 'bold, italic, underline, strikethrough, separator, justifyleft,  justifycenter, justifyright,  justifyfull, separator, link, unlink , separator, fullscreen',
                    theme_advanced_buttons2: '',
                    theme_advanced_buttons3: '',
                    theme_advanced_buttons4: '',
                    theme_advanced_toolbar_location : 'top',
                    theme_advanced_toolbar_align : 'left',
                    width: '100%',
                    height: '200px',
                    onchange_callback : 'hayCambios'
                    }
               )
               
               $('#newfp').button(
                    {
                         icons: {
                              primary: "ui-icon-plus"
                              },
                         text: false
                    }
               ).click(
                    function(){
                         $('#up_div').fadeIn()
                         params['tipo_media'] = $(this).attr('rel')
                    }
               )
               
               $( 'ul.gallery > li' ).live(
                    'click',
                    function( event ) {
                         var $item = $( this ),
                              $target = $( event.target )

                         if ( $target.is( 'a.ui-icon-trash' ) ) {
                              deleteImage( $target )
                         } else if ( $target.is( 'a.ui-icon-zoomin' ) ) {
                              viewLargerImage( $target )
                         }
                         return false
                    }
               )
             
               $('#FPul').sortable(
                    {
                         tolerance: 'pointer',
                         update: 
                              function(event, ui) {
                                   reordenar(ui.item)
                              }
                    }
               )
               $('#FPul').disableSelection()
              
               var settings = 
                    {
                         debug: false,
                         upload_url: '{% url mdm.views.subidapag %}',
                         flash_url: '{{ MEDIA_URL }}mdm/js/swfupload.swf',
                         button_placeholder_id: 'upload_btn',
                         button_width: '96',
                         button_height: '29',
                         button_image_url : '{{ MEDIA_URL }}mdm/js/examina.png',
                         file_types_description:  'Imágenes', 
                         file_types: '*.png;*.jpg;*.gif',
                         file_size_limit : '3 MB', 
                         file_upload_limit : 100,
                         file_queue_limit : 0,
                         custom_settings : {
                              progressTarget : "fsUploadProgress",
                         },
                         button_cursor: SWFUpload.CURSOR.HAND,
                          // The event handler functions are defined in handlers.js
                         file_queued_handler : fileQueued,
                         file_queue_error_handler : fileQueueError,
                         file_dialog_complete_handler : fileDialogComplete,
                         upload_start_handler : uploadStart,
                         upload_progress_handler : uploadProgress,
                         upload_error_handler : uploadError,
                         upload_success_handler : uploadSuccess,
                         upload_complete_handler : uploadComplete,
                         queue_complete_handler : queueComplete // Queue plugin event 
                    }
                    
               swfu = new SWFUpload(settings)               
               
               $('#cerrarFrm').button().click(
                    function() {
                         if($('#divStatus').text() != '0 archivos subidos') {
                              cargaFotos(actual)
                              $('#divStatus').text('0 archivos subidos')
                         }
                         $('#up_div').fadeOut()
                    }
               )
               
               params['promo_id'] = $('#promociones div h3').attr('id').replace('promo', '')
               $(document).ajaxStop($.unblockUI)
               setTimeout("cargaPromo($('#promociones div h3').attr('id'))", 500)
          }
     )
     
     function cargaPromo(id){
          espera()
          $.post(
               '{% url datospag %}' + '/' + id.replace('promo', ''), 
               '',
               function(data){
                   rellenar(data)
               },
               'json'
          )
          if (actual) $('#' + actual).parent().removeClass('sombra')
          $('#' + id).parent().addClass('sombra')
          actual = id
          dirty = false
          if ($('#guardar1').is(':visible')) $('#guardar1').fadeOut()
          setTimeout('cargaFotos()', 500)
          
     }
          
     function cargaFotos(){
          $.post(
               '{% url fotospag %}' + '/' + actual.replace('promo', ''), 
               '',
               function(data){
                   fotos(data)
               },
               'json'
          )
     }
     
     function rellenar(dat) {
          var ds = tinyMCE.get('texto')
          if (ds) ds.setContent(dat.texto)
     }
     
     function fotos(datos) {
          $('#FPul').empty()
          var dat = sortObject(datos)
          for (x in dat) {
               cur = dat[x]
               im =  '<li class="bordea ui-widget-content ui-corner-tr" id="img_' + cur.tipo + '_' + cur.id + '"><h5 class="ui-widget-header titulofoto"></h5><div class="imgcont"><img alt="' + cur.ds + '" src="'
               if (cur.thumb != '') {
                    im += cur.thumb
               } else {
                    im += cur.foto
               }
               im += '" width="100"/></div><a href="' + cur.foto + '" title="Ampliar" class="ui-icon ui-icon-zoomin">Ampliar</a>'
               im += '<span>' + cur.size[0] + 'x' + cur.size[1] + '</span><a href="#" title="Borrar" class="ui-icon ui-icon-trash" rel="' + cur.id + '">Borrar</a></li>'
               $('#FPul').append(im)               
          }
     }
     
     function hayCambios($target){
          dirty = true
          if (!$('#guardar1').is(':visible')) $('#guardar1').fadeIn()
     }
     
     function guardar() {
          var fr = {}
          fr['texto'] = tinyMCE.get('texto').getContent()  
          $.post(
               '{% url actualizapag %}', 
               {'promo_id': actual.replace('promo', ''), 'campos': JSON.stringify(fr) }
          )             
          $('#guardar1').fadeOut()
          dirty = false          
     }
       
     function espera() {
          $.blockUI({message: '<h3><img src="{{MEDIA_URL}}img/superbgloading.gif" style="vertical-align: middle; margin: 5px">Espere, por favor...</h3>'})
     }
     
     // image preview function, demonstrating the ui.dialog used as a modal window
     function viewLargerImage( $link ) {
          var src = $link.attr( 'href' ),
          title = $link.siblings( 'img' ).attr( 'alt' ),
          $modal = $( 'img.chopo[src$="' + src + '"]' )
          if ( $modal.length) {
               $modal.dialog( 'open' )
          } else {
               var img = $( '<img class="chopo" alt="' + title + '" style="display: none padding: 8px" />' )
                    .attr( 'src', src ).appendTo( 'body' )
               var ancho = parseInt($link.siblings('span').text().split('x')[0]) + 35
               setTimeout(function() {
                    img.dialog({
                         title: title,
                         modal: true,
                         minWidth: ancho,
                         positon: 'top',               
                         resizable: false
                    })
               }, 100 )
          }
     }

     function deleteImage($cual) {
          if (confirm('¿Borrar la imagen?')) {
               $.post(
                    '{% url borrafotopag %}', 
                    {'media_id':  $cual.attr('rel')}
               )
               cargaFotos(actual)
          }         
     }
     
     function reordenar() {
          espera()
          var arr = $('#FPul').sortable('toArray')
          var n = 0
          for (x in arr) {
              $.post(
                    '{% url ordenafotopag %}', 
                    {'media_id': arr[x].split('_')[2], 'orden': n}
               )
               n++               
          }
          
     }
     
     function sortObject(o) {
         var sorted = {},
         key, a = [];

         for (key in o) {
             if (o.hasOwnProperty(key)) {
                     a.push(key);
             }
         }

         a.sort();

         for (key = 0; key < a.length; key++) {
             sorted[a[key]] = o[a[key]];
         }
         return sorted;
     }

     </script>
{% endblock  %}
